import { Col, Form, Input, message, Modal, Row, Select, Spin } from "antd";
import React from "react";
import axios from "../../../../components/service/request";

const EditModal = ({ isModalVisible, cancelModal, value, reload, baseUir }) => {

    const [confirmLoading, setConfirmLoading] = React.useState(false);
    const [spinLoading, setSpinLoading] = React.useState(false);
    const [title, setTitle] = React.useState("新增用户");

    const [permissionOptions, setPermissionOptions] = React.useState(null);

    const [form] = Form.useForm();
    let Option = Select.Option;


    React.useEffect(() => {
        if (isModalVisible) {
            setSpinLoading(true)
            // 获取权限列表
            axios.get(baseUir + '/getPermissions').then(res => {
                console.log('权限列表数据:', res.data); // 打印返回的数据，方便查看

                let options = [];
                if (res.data) {
                    // 使用 Set 去重，确保权限不重复
                    const uniquePermissions = Array.from(
                        new Set(res.data.map(JSON.stringify))
                    ).map(JSON.parse);

                    console.log('去重后的权限列表:', uniquePermissions); // 打印去重后的数据

                    options = uniquePermissions.map(r => (
                        <Option key={r.id} value={r.id}>
                            {r.permissionName}
                        </Option>
                    ));
                }
                setPermissionOptions(options);
                setSpinLoading(false);
            });

            if (value) {
                setTitle("修改角色信息");
                // 处理已选权限，确保不重复
                const uniquePermissions = Array.from(
                    new Set(value.permissions.map(JSON.stringify))
                ).map(JSON.parse);

                console.log('当前角色的权限:', uniquePermissions); // 打印当前角色的权限

                const permissionIds = uniquePermissions.map(p => p.id);

                form.setFieldsValue({
                    id: value.id,
                    name: value.name,
                    permissionIds: permissionIds,
                    description: value.description,
                    formatCreateTime: value.formatCreateTime
                });
            }
        }
    }, [baseUir, form, isModalVisible, value]);

    const handleOk = () => {
        setConfirmLoading(true)
        form.validateFields()
            .then((values) => {
                form.resetFields();
                // 根据是否有value判断是编辑还是新增
                const url = value
                    ? baseUir + "/save"    // 编辑
                    : baseUir + "/add";    // 新增u
                axios.post(url, values).then(res => {
                    if (res.code === 200) {
                        message.info(res.msg)
                        cancelModal()
                        reload()
                    } else {
                        message.info(res.msg)
                    }
                })
            })
        setConfirmLoading(false)
    }

    const handleCancel = () => {
        form.resetFields()
        cancelModal()
    }

    const checkRoleName = (name) => {
        let param
        if (value) {
            param = { name: name, roleId: value.id }
        } else {
            param = { name: name }
        }

        return new Promise(resolve => {
            axios.post(baseUir + '/checkRoleName', param)
                .then(res => {
                    resolve(res)
                })
        });

    }

    return (
        <Modal title={title}
            visible={isModalVisible}
            onOk={handleOk}
            onCancel={handleCancel}
            okText={'保存'}
            confirmLoading={confirmLoading}
            cancelText={'取消'}
            width={800}
        >
            <Spin spinning={spinLoading}>
                <Form form={form}
                    // layout={{span: 2, offset: 2}}
                    labelAlign={'right'}
                    layout={'vertical'}

                >
                    <Form.Item name="id" hidden={true}>
                        <Input />
                    </Form.Item>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item name="name" label="角色名" rules={[
                                {
                                    required: true,
                                    message: "必须填写角色名！",
                                },
                                ({ getFieldValue }) => ({
                                    async validator(_, roleNameValue) {
                                        if (roleNameValue) {
                                            let res = await checkRoleName(roleNameValue);
                                            if (res.code === 200) {
                                                return Promise.resolve();
                                            } else {
                                                return Promise.reject(new Error(res.msg));
                                            }
                                        }
                                    }
                                })
                            ]}>
                                {
                                    <Input />
                                }
                            </Form.Item>
                        </Col>

                        <Col span={12}>
                            <Form.Item name="permissionIds" label="权限" rules={[{ required: true, message: "至少选中一个权限！" }]}>
                                <Select
                                    placeholder="请选择权限"
                                    style={{ width: '100%' }}
                                    allowClear
                                    mode="multiple"
                                >
                                    {permissionOptions}
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>

                        <Col span={12}>
                            <Form.Item name="description" label="备注">
                                {
                                    <Input />
                                }
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item name="formatCreateTime" label="创建时间" >
                                <Input disabled={true} />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Spin>

        </Modal>
    );

}

export default EditModal;
